﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using Beyondbit.Desktop.Common;
using RBS.Common;
using RBS.Common.DEncrypt;
using RBS.Common.JsonEntity;
using RBS.Core.Model;
using Webdiyer.WebControls.Mvc;

namespace RBS.Admin.Controllers
{
    public class SysController : BaseController
    {
        //
        // GET: /Sys/
        #region 日志管理
      /*  public ActionResult LogManage()
        {
            ChkAdminLevel("manager_list", RBSEnums.ActionEnum.View.ToString()); //检查权限 
            var logsModel = RptBind("id>0" , "add_time desc,id desc");
            return View(logsModel);
        }*/
       
        public ActionResult LogManage(int id = 1, string kword = null)
        { 
            int pageSize = 10; 
            ChkAdminLevel("manager_log", RBSEnums.ActionEnum.View.ToString()); //检查权限  
            Dictionary<string, string> pagerParams = null;

            string strWhere = "id>0" + CombSqlTxt(kword);
            const string orderby = "add_time desc,id desc";
            var bll = new Core.BLL.manager_log();
           
            var startIndex = id;

            int totalItems = 0; //要分页的总记录数
            DataTable dt = bll.GetList(pageSize, startIndex, strWhere, orderby, out totalItems);
            //PagedList构造函数
            var list = IListDataSet.DataTableToIList<RBS.Core.Model.manager_log>(dt);
            var arts = new PagedList<RBS.Core.Model.manager_log>(list, id, pageSize, totalItems);
            return View(arts); 
        }  
        public Dictionary<string, string> GetJsonData(string jsonData)
        {
            if (jsonData.Length > 0)
            {
                jsonData = jsonData.Trim().Substring(1, jsonData.Length - 2);
                string[] arrayData = jsonData.Split(',');
                if (arrayData.Length > 0)
                {
                    var parameter = new Dictionary<string, string>();
                    foreach (string t in arrayData)
                    {
                        var key = t.Substring(0, (t.IndexOf(":", System.StringComparison.Ordinal))).Trim().ToLower();
                        string value = t.Substring(t.IndexOf(":", System.StringComparison.Ordinal) + 1).Trim();
                        parameter.Add(key, value);
                    }
                    return parameter;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }

        }
        protected string CombSqlTxt(string keywords)
        { 
            var strTemp = new StringBuilder();
            if (keywords == null)
            {
                return "";
            }
            keywords = keywords.Replace("'", "");
            if (!string.IsNullOrEmpty(keywords))
            {
                strTemp.Append(" and (user_name like  '%" + keywords + "%' or action_type like '%" + keywords + "%')");
            }
            return strTemp.ToString();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult LogDelete()
        {
            var ret = new JsonReturnMessages();
            ChkAdminLevel("manager_log", RBSEnums.ActionEnum.Delete.ToString()); //检查权限  
            int sucCount= new RBS.Core.BLL.manager_log().Delete(7); 
            AddAdminLog(RBSEnums.ActionEnum.Delete.ToString(), "删除管理日志" + sucCount + "条"); //记录日志
            ret.IsSuccess = true;
            ret.Msg = "操作成功";
            ret.Data =  Url.Action("LogManage", "Sys");
            return Json(ret);
        }

        
        #endregion

        #region 后台用户管理
        //管理员列表
        public ActionResult AdminUserManager(int id = 1, string kword = null)
        {
              int pageSize = 10; 
              ChkAdminLevel("manager_list", RBSEnums.ActionEnum.View.ToString()); //检查权限
            var  bll = new Core.BLL.manager();
             manager model = GetAdminInfo(); //取得当前管理员信息
            if (kword != null) kword = kword.Replace("'", "");
            var strTemp =new StringBuilder();
                if (!string.IsNullOrEmpty(kword))
                {
                    strTemp.Append(" and (user_name like  '%" + kword + "%' or real_name like '%" + kword + "%' or email like '%" + kword + "%')");
                }
                string strWhere = "role_type>=" + model.role_type + strTemp;
                const string orderby = "add_time desc,id desc";
                var startIndex = id;

                int totalItems = 0; //要分页的总记录数
                DataTable dt = bll.GetList(pageSize, startIndex, strWhere, orderby, out totalItems).Tables[0];
                //PagedList构造函数
                var list = IListDataSet.DataTableToIList<RBS.Core.Model.manager>(dt);
                var arts = new PagedList<RBS.Core.Model.manager>(list, id, pageSize, totalItems);
                return View(arts);  
        }
    
        public ActionResult AdminUserEdit(int id = 0)
        {
            
            ViewBag.defaultpassword = ""; 
            var model = new manager();
            if (id != 0)
            {
                ViewBag.defaultpassword = RBSKeys.Defaultpassword; 
                var bll = new RBS.Core.BLL.manager();
                model = bll.GetModel(id);
            }
            ViewBag.role = new SelectList(RoleBind(model.role_id), "Value", "Text",model.role_id);   
            ViewData.Model = model;
            
            return View();
        }
        [HttpPost]
        public ActionResult AdminUserEdit(FormCollection collection)
        {  
            var model = new manager
                {
                    email = collection["email"],
                    is_lock = int.Parse(collection["is_lock"]),
                    add_time = DateTime.Now, 
                    real_name = collection["real_name"],
                    telephone = collection["telephone"],
                    user_name = collection["user_name"],
                    salt = collection["salt"] == "" ? Utils.GetCheckCode(6) : collection["salt"]
                }; 
            //密码修改
            model.password = collection["txtPassword1"] != RBSKeys.Defaultpassword ? DESEncrypt.Encrypt(collection["txtPassword1"], model.salt) : collection["password"];
            //角色绑定
            model.role_id = Convert.ToInt32(collection["role_id"]);
            var rolemodel=  new RBS.Core.BLL.manager_role().GetModel(model.role_id);
            model.role_name = rolemodel.role_name;
            model.role_type = rolemodel.role_type;
            var bll = new RBS.Core.BLL.manager();
            if (collection["id"] != "0")
            {
                model.id = Convert.ToInt32(collection["id"]);
                bll.Update(model);
                AddAdminLog(RBSEnums.ActionEnum.Edit.ToString(), "修改管理员:" + model.user_name); //记录日志
            }
            else
            {
              
                bll.Add(model);
                AddAdminLog(RBSEnums.ActionEnum.Add.ToString(), "添加管理员:" + model.user_name); //记录日志
            } 
            return RedirectToAction("AdminUserManager");
        }


        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult AdminUserDelete(string ids, string returnUrl)
        {
            var ret = new JsonReturnMessages();
            ChkAdminLevel("RoleManage", RBSEnums.ActionEnum.Delete.ToString()); //检查权限 
            try
            {
                foreach (var id in ids.TrimEnd(',').Split(',').ToList())
                {
                    new RBS.Core.BLL.manager().Delete(int.Parse(id));
                }
            }
            catch (Exception exception)
            {
                ret.IsSuccess = false;
                ret.Msg = "操作失败！";
                return Json(ret);
            }
            AddAdminLog(RBSEnums.ActionEnum.Delete.ToString(), "删除管理员信息"); //记录日志
            ret.IsSuccess = true;
            ret.Msg = "操作成功";
            ret.Data = !string.IsNullOrEmpty(returnUrl) ? returnUrl : Url.Action("AdminUserManager", "Sys");
            return Json(ret);
        }
        #endregion

        #region 角色管理

        public ActionResult RoleManage(int id = 0, string kword = null)
        { 
            ChkAdminLevel("manager_role", RBSEnums.ActionEnum.View.ToString()); //检查权限
            Core.Model.manager model = GetAdminInfo(); //取得当前管理员信息

            //绑定角色类别
            ViewData.Model = !string.IsNullOrEmpty(kword) ? RptBind("role_type>=" + model.role_type + "and role_name like '%" + kword + "%'") : RptBind("role_type>=" + model.role_type);

          
            return View();
        }
        private IList<RBS.Core.Model.manager_role> RptBind(string _strWhere)
        {   
            var bll = new Core.BLL.manager_role(); 
            DataSet dataSet = bll.GetList(_strWhere);
           return  IListDataSet.DataSetToIList<RBS.Core.Model.manager_role>(dataSet, 0);   
        }
       
        public ActionResult RoleEdit(int id=0)
        {
            var model = new manager_role();
            var rvalues = new List<manager_role_value> ();
            if (id != 0)
            {
                var roleBll = new RBS.Core.BLL.manager_role();
                model = roleBll.GetModel(id);

                if (model.manager_role_values!=null)
                      rvalues = model.manager_role_values;
            } 

            //获取导航列表
            var navbll = new RBS.Core.BLL.SysNavigation();
            DataTable dt = navbll.GetList(0, RBSEnums.NavigationEnum.System.ToString());
            ViewBag.NavList = IListDataSet.DataTableToIList<RBS.Core.Model.SYS_Navigation>(dt);


            ViewBag.Nav = rvalues;
           
            //系统角色
            ViewBag.roletype = new SelectList(new List<SelectListItem>
                {
                    new SelectListItem {Text = "请选择类型...", Value = ""},
                    new SelectListItem {Text = "超级用户", Value = "1"},
                    new SelectListItem {Text = "系统用户", Value = "2"}
                }, "Value", "Text", model.role_type); 
            ViewData.Model = model;
        

            return View();
        }

        [HttpPost]
        public ActionResult RoleEdit(FormCollection  collection)
        {

            var ls = new List<manager_role_value>();
            for (int i = 2; i < collection.Count; i++)
            {
                var navName = collection.AllKeys[i];
                var navvalues = collection[i];
                var navvalue = navvalues.Split(',');
                ls.AddRange(navvalue.Select(s => new manager_role_value {nav_name = navName, action_type = s}));
            } 
            var model = new manager_role
                {
                    role_name = collection["role_name"],
                    role_type = Convert.ToInt32(collection["role_type"]),
                    is_sys = Convert.ToInt32(collection["is_sys"]),
                    manager_role_values = ls
                };
                 var bll = new RBS.Core.BLL.manager_role();

            if (collection["id"] != null && Convert.ToInt32(collection["id"]) > 0)
            {
                model.id = Convert.ToInt32(collection["id"]);
            }

            if (model.id > 0)
            {
                if (bll.Update(model))
                {
                    AddAdminLog(RBSEnums.ActionEnum.Edit.ToString(), "修改管理角色:" + model.role_name); //记录日志 
                    return RedirectToAction("RoleManage");
                } 
            }
            else
            {
                if (bll.Add(model) > 0)
                {
                    AddAdminLog(RBSEnums.ActionEnum.Add.ToString(), "添加管理角色:" + model.role_name); //记录日志 
                    return RedirectToAction("RoleManage");
                } 
            }
             
           return View("RoleEdit");
        } 
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult RoleDelete(string ids, string returnUrl)
        {
            var ret = new JsonReturnMessages();
            ChkAdminLevel("RoleManage", RBSEnums.ActionEnum.Delete.ToString()); //检查权限 
            try
            {
                foreach (var id in ids.TrimEnd(',').Split(',').ToList())
                {
                    new RBS.Core.BLL.manager_role().Delete(int.Parse(id));
                }
            }
            catch (Exception exception)
            {
                ret.IsSuccess = false;
                ret.Msg = "操作失败，当前角色下面存用户！";
                return Json(ret);
            }
            AddAdminLog(RBSEnums.ActionEnum.Delete.ToString(), "删除角色信息"); //记录日志
            ret.IsSuccess = true;
            ret.Msg = "操作成功";
            ret.Data = !string.IsNullOrEmpty(returnUrl) ? returnUrl : Url.Action("RoleManage", "Sys");
            return Json(ret);
        }

        #endregion

        #region 后台导航管理 
        public ActionResult NavManage()
        {
            IList<SYS_Navigation> list = new List<SYS_Navigation>(); 
            ChkAdminLevel("app_navigation_list", RBSEnums.ActionEnum.View.ToString());
            RBS.Core.BLL.SysNavigation bll = new RBS.Core.BLL.SysNavigation();
            DataTable dt = bll.GetList(0, RBSEnums.NavigationEnum.System.ToString()); 
            ViewData.Model=IListDataSet.DataTableToIList<RBS.Core.Model.SYS_Navigation>(dt);  
            return View();
        }
        public SelectList action_type { get; set; } 
        public ActionResult NavCreate(int id=0)
        {
            
            this.ViewData["ddlParentId"] = TreeBind(RBSEnums.NavigationEnum.System.ToString(), id);
            return View();
        } 
        [HttpPost]
        public ActionResult NavCreate(FormCollection collection)
        {
            string action_type = string.Empty;
            for (int i = 9; i <collection.AllKeys.Length; i++)
            {
                action_type += collection.AllKeys[i]+",";
            }
            action_type = action_type.TrimEnd(',');
            RBS.Core.Model.manager admin = GetAdminInfo();  
            var model = new SYS_Navigation()
                {
                    nav_type = RBSEnums.NavigationEnum.System.ToString(),
                    parent_id = Convert.ToInt32 (collection["ddlParentId"]),
                    name = collection["name"],
                    title = collection["title"],
                    sub_title = collection["sub_title"],
                    link_url = collection["link_url"],
                    sort_id = Convert.ToInt32(collection["sort_id"]),
                    is_lock = collection["cbIsLock"]=="false"?0:1, 
                  //  class_list =  collection["class_list"],
                  //  class_layer =  collection["class_layer"], 
                    action_type = action_type,
                    is_sys =  0, 
                    channel_id = 0,
                    remark =  collection["remark"]
                };
            new RBS.Core.BLL.SysNavigation().Add(model);
            return RedirectToAction("NavManage");
            

        }

        public ActionResult NavEdit(int id=0)
        { 
            var nav = new RBS.Core.BLL.SysNavigation().GetModel(id);
            ViewData.Model = nav;
            ViewBag.actionType = nav.action_type.Split(',');
            this.ViewData["ddlParentId"] = TreeBind(RBSEnums.NavigationEnum.System.ToString(), nav.parent_id); 
            return View();
        }
        [HttpPost]
        public ActionResult NavEdit(int id ,FormCollection collection)
        {
            string action_type = string.Empty;
            for (int i = 9; i < collection.AllKeys.Length; i++)
            {
                action_type += collection.AllKeys[i] + ",";
            }
            action_type = action_type.TrimEnd(',');
            RBS.Core.Model.manager admin = GetAdminInfo();
            var model = new SYS_Navigation()
            {
                id = id,
                nav_type = RBSEnums.NavigationEnum.System.ToString(),
                parent_id = Convert.ToInt32(collection["ddlParentId"]),
                name = collection["name"],
                title = collection["title"],
                sub_title = collection["sub_title"],
                link_url = collection["link_url"],
                sort_id = Convert.ToInt32(collection["sort_id"]),
                is_lock = collection["cbIsLock"] == "false" ? 0 : 1, 
                action_type = action_type,
                is_sys = 0,
                channel_id = 0,
                remark = collection["remark"]
            };
            new RBS.Core.BLL.SysNavigation().Update(model);
            return RedirectToAction("NavManage");
        }




        #region 酒店后台链接
        public ActionResult NavWebSiteManage()
        {
            IList<SYS_Navigation> list = new List<SYS_Navigation>();
            ChkAdminLevel("app_navigation_list", RBSEnums.ActionEnum.View.ToString());
            RBS.Core.BLL.SysNavigation bll = new RBS.Core.BLL.SysNavigation();
            DataTable dt = bll.GetList(0, RBSEnums.NavigationEnum.WebSite.ToString());
            ViewData.Model = IListDataSet.DataTableToIList<RBS.Core.Model.SYS_Navigation>(dt);
            return View();
        }
  
        public ActionResult NavWebSiteCreate(int id = 0)
        {

            this.ViewData["ddlParentId"] = TreeBind(RBSEnums.NavigationEnum.WebSite.ToString(), id);
            return View();
        }
        [HttpPost]
        public ActionResult NavWebSiteCreate(FormCollection collection)
        {
            string action_type = string.Empty;
            for (int i = 9; i < collection.AllKeys.Length; i++)
            {
                action_type += collection.AllKeys[i] + ",";
            }
            action_type = action_type.TrimEnd(',');
            RBS.Core.Model.manager admin = GetAdminInfo();
            var model = new SYS_Navigation()
            {
                nav_type = RBSEnums.NavigationEnum.WebSite.ToString(),
                parent_id = Convert.ToInt32(collection["ddlParentId"]),
                name = collection["name"],
                title = collection["title"],
                sub_title = collection["sub_title"],
                link_url = collection["link_url"],
                sort_id = Convert.ToInt32(collection["sort_id"]),
                is_lock = collection["cbIsLock"] == "false" ? 0 : 1,
                //  class_list =  collection["class_list"],
                //  class_layer =  collection["class_layer"], 
                action_type = action_type,
                is_sys = 0,
                channel_id = 0,
                remark = collection["remark"]
            };
            new RBS.Core.BLL.SysNavigation().Add(model);
            return RedirectToAction("NavWebSiteManage");


        }

        public ActionResult NavWebSiteEdit(int id = 0)
        {
            var nav = new RBS.Core.BLL.SysNavigation().GetModel(id);
            ViewData.Model = nav;
            ViewBag.actionType = nav.action_type.Split(',');
            this.ViewData["ddlParentId"] = TreeBind(RBSEnums.NavigationEnum.WebSite.ToString(), nav.parent_id);
            return View();
        }
        [HttpPost]
        public ActionResult NavWebSiteEdit(int id, FormCollection collection)
        {
            string action_type = string.Empty;
            for (int i = 9; i < collection.AllKeys.Length; i++)
            {
                action_type += collection.AllKeys[i] + ",";
            }
            action_type = action_type.TrimEnd(',');
            RBS.Core.Model.manager admin = GetAdminInfo();
            var model = new SYS_Navigation()
            {
                id = id,
                nav_type = RBSEnums.NavigationEnum.WebSite.ToString(),
                parent_id = Convert.ToInt32(collection["ddlParentId"]),
                name = collection["name"],
                title = collection["title"],
                sub_title = collection["sub_title"],
                link_url = collection["link_url"],
                sort_id = Convert.ToInt32(collection["sort_id"]),
                is_lock = collection["cbIsLock"] == "false" ? 0 : 1,
                action_type = action_type,
                is_sys = 0,
                channel_id = 0,
                remark = collection["remark"]
            };
            new RBS.Core.BLL.SysNavigation().Update(model);
            return RedirectToAction("NavWebSiteManage");
        }
        #endregion




        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult NavDelete(string ids, string returnUrl)
        {
            var ret = new JsonReturnMessages();
            ChkAdminLevel("app_navigation_list", RBSEnums.ActionEnum.Delete.ToString()); //检查权限 
            try
            {
                foreach (var id in ids.TrimEnd(',').Split(',').ToList())
                {
                    new RBS.Core.BLL.SysNavigation().Delete(int.Parse(id));
                }
            }
            catch (Exception exception)
            {
                ret.IsSuccess = false;
                ret.Msg = "操作失败";
                return Json(ret);
            }
            AddAdminLog(RBSEnums.ActionEnum.Delete.ToString(), "删除导航信息"); //记录日志
            ret.IsSuccess = true;
            ret.Msg = "操作成功"; 
            ret.Data = !string.IsNullOrEmpty(returnUrl) ? returnUrl : Url.Action("NavManage", "Sys");
            return Json(ret);
        }
        #endregion

        #region 数据字典管理  
        public ActionResult DictInfoIndex(int dicId=0)
        {
            string sqlWhere = string.Empty;
            if (dicId != 0)
                sqlWhere = " 1=1";

            ViewData.Model= new RBS.Core.BLL.SYS_DictInfo().GetModelList(sqlWhere);
            ViewBag.dicId = dicId;
            return View();
        }
        public ActionResult DictInfoEdit()
        {
            
            var id = Convert.ToInt32(Request["id"]);
             var action  = Request["action"];
            if (action != null && action == RBS.Common.RBSEnums.ActionEnum.Delete.ToString())
            {
               //delete
            }
             
            var parentName = "数据字典"; 
            var dictinfo=new RBS.Core.BLL.SYS_DictInfo().GetModel(id);
            ViewData.Model = dictinfo;
            if (dictinfo.ParentID != 0)
            {
                parentName = new RBS.Core.BLL.SYS_DictInfo().GetModel(dictinfo.ParentID).DictName;
            }
            var items = new List<SelectListItem>
                {
                    new SelectListItem {Text = parentName, Value = dictinfo.ParentID.ToString()}
             };
            this.ViewData["ParentId"] = items; 

            return View();
        }
        [HttpPost]
        public ActionResult DictInfoEdit(int id ,FormCollection collection)
        {
            RBS.Core.Model.manager admin = GetAdminInfo();
            var model = new SYS_DictInfo
            {
                DictID = Convert.ToInt32( collection["DictID"]),
                LastUpdateUserName = admin.user_name,
                LastUpdateUserFullName = admin.user_name,
                LastUpdateTime = DateTime.Now,// collection["LastUpdateTime"],
                CreateUserName = collection["CreateUserName"],
                CreateUserFullName = collection["CreateUserFullName"],
                CreateDateTime = DateTime.Parse(collection["CreateDateTime"]),
                DictName = collection["DictName"],
                DictCode = collection["DictCode"],
                DictType = 0,//collection["DictType"],
                ParentID = int.Parse(collection["ParentId"]),
                Path = collection["Path"],
                Sequence = Convert.ToInt32(collection["Sequence"]),
                SQLCMD = collection["SQLCMD"],
                Remark = collection["Remark"]
            };
            new RBS.Core.BLL.SYS_DictInfo().Update(model);
            return RedirectToAction("DictInfoIndex", new { dicId =model.ParentID});
            
        }
        public ActionResult DictInfoCreate()
        { 
            var parentId = Convert.ToInt32(Request["parentid"]);
            var parentName = "数据字典";
            if (parentId != 0)
            { 
               parentName = new RBS.Core.BLL.SYS_DictInfo().GetModel(parentId).DictName;
            } 
            var  items = new List<SelectListItem>
                {
                    new SelectListItem {Text = parentName, Value = parentId.ToString()}
                };
            this.ViewData["ParentId"] = items; 

            return View();
        }
        [HttpPost]
        public ActionResult DictInfoCreate(FormCollection collection)
        {

            RBS.Core.Model.manager admin = GetAdminInfo();  
            var model = new SYS_DictInfo
                {
                    LastUpdateUserName = admin.user_name,
                    LastUpdateUserFullName = admin.user_name,
                    LastUpdateTime = DateTime.Now,// collection["LastUpdateTime"],
                    CreateUserName = admin.user_name,
                    CreateUserFullName = admin.user_name,
                    CreateDateTime =  DateTime.Now,// collection["CreateDateTime"],
                    DictName = collection["DictName"],
                    DictCode = collection["DictCode"],
                    DictType = 0,//collection["DictType"],
                    ParentID = int.Parse(collection["ParentId"]),
                    Path = collection["Path"],
                    Sequence = Convert.ToInt32(collection["Sequence"]),
                    SQLCMD = collection["SQLCMD"],
                    Remark = collection["Remark"]
                };
            new RBS.Core.BLL.SYS_DictInfo().Add(model);
            return RedirectToAction("DictInfoIndex", new { dicId = model.ParentID });
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult DicInfoList(int parentid)
        { 
            string sqlWhere = string.Empty;
            if (parentid != 0)
                sqlWhere = " parentid=" + parentid;
            else
            {
                sqlWhere = " parentid=0";
            } 
            var  ret =new RBS.Core.BLL.SYS_DictInfo().GetModelList(sqlWhere);
            return Json(ret);
        }

        [HttpPost]
        public JsonResult DictInfoDelete(int id = 0)
        { 
             var ret = new JsonReturnMessages();
            if (id == 0)
            {
                ret.IsSuccess = false;
                ret.Msg = "操作失败";
                return Json(ret);
            }
            else
            {
                ret.IsSuccess= new RBS.Core.BLL.SYS_DictInfo().DeleteChild(id);  
                ret.Msg = "操作成功"; 
                ret.Data = Url.Action("DictInfoIndex");
                return Json(ret);
            }  
        }
        #endregion


        #region 系统设置

        public ActionResult SysConfig()
        {
            ChkAdminLevel("site_config", RBSEnums.ActionEnum.View.ToString()); //检查权限

            var bll = new RBS.Core.BLL.Siteconfig();
            Siteconfig model = bll.loadConfig();
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SysConfig(FormCollection collection)
        {

            ChkAdminLevel("site_config", RBSEnums.ActionEnum.Edit.ToString()); //检查权限
            var bll = new RBS.Core.BLL.Siteconfig();
            Siteconfig model = bll.loadConfig();
            try
            {
                model.webname = collection["webname"];
                model.weburl = collection["weburl"] ;
                model.weblogo = collection["weblogo"];
                model.webcompany = collection["webcompany"];
                model.webaddress = collection["webaddress"];
                model.webtel = collection["webtel"];
                model.webfax = collection["webfax"];
                model.webmail = collection["webmail"];
                model.webcrod = collection["webcrod"] ;
                model.webtitle = collection["webtitle"] ;
                model.webkeyword = collection["webkeyword"];
                model.webdescription = Utils.DropHTML(collection["webdescription"]);
                model.webcopyright = collection["webcopyright"];

                model.webpath = collection["webpath"];
                model.webmanagepath = collection["webmanagepath"];
              //  model.staticstatus = Utils.StrToInt(staticstatus.SelectedValue, 0);
                model.staticextension = collection["staticextension"];
              /*  if (memberstatus.Checked == true)
                {
                    model.memberstatus = 1;
                }
                else
                {
                    model.memberstatus = 0;
                }
                if (commentstatus.Checked == true)
                {
                    model.commentstatus = 1;
                }
                else
                {
                    model.commentstatus = 0;
                }
                if (logstatus.Checked == true)
                {
                    model.logstatus = 1;
                }
                else
                {
                    model.logstatus = 0;
                }
                if (webstatus.Checked == true)
                {
                    model.webstatus = 1;
                }
                else
                {
                    model.webstatus = 0;
                }*/
                model.webclosereason = collection["webclosereason"];
                model.webcountcode = collection["webcountcode"];

                model.smsusername = collection["smsusername"];
                //判断密码是否更改
                if (collection["smspassword"].Trim() != "" && collection["smspassword"].Trim() != RBSKeys.Defaultpassword)
                {
                    model.smspassword = Utils.MD5(collection["smspassword"].Trim());
                }

                model.emailsmtp = collection["emailsmtp"];
                model.emailport = Utils.StrToInt(collection["emailport"].Trim(), 25);
                model.emailfrom = collection["emailfrom"];
                model.emailusername = collection["emailusername"];
                //判断密码是否更改
                if (collection["emailpassword"].Trim() != RBSKeys.Defaultpassword)
                {
                    model.emailpassword = DESEncrypt.Encrypt(collection["emailpassword"], model.sysencryptstring);
                }
                model.emailnickname = collection["emailnickname"];

                model.filepath = collection["filepath"];
              //  model.filesave = Utils.StrToInt(filesave.SelectedValue, 2);
                model.fileextension = collection["fileextension"];
                model.attachsize = Utils.StrToInt(collection["attachsize"].Trim(), 0);
                model.imgsize = Utils.StrToInt(collection["imgsize"].Trim(), 0);
                model.imgmaxheight = Utils.StrToInt(collection["imgmaxheight"].Trim(), 0);
                model.imgmaxwidth = Utils.StrToInt(collection["imgmaxwidth"].Trim(), 0);
                model.thumbnailheight = Utils.StrToInt(collection["thumbnailheight"].Trim(), 0);
                model.thumbnailwidth = Utils.StrToInt(collection["thumbnailwidth"].Trim(), 0);
              //  model.watermarktype = Utils.StrToInt(collection["watermarktype.SelectedValue"], 0);
                model.watermarkposition = Utils.StrToInt(collection["watermarkposition"].Trim(), 9);
                model.watermarkimgquality = Utils.StrToInt(collection["watermarkimgquality"].Trim(), 80);
                model.watermarkpic = collection["watermarkpic"];
                model.watermarktransparency = Utils.StrToInt(collection["watermarktransparency"].Trim(), 5);
                model.watermarktext = collection["watermarktext"];
                model.watermarkfont = collection["watermarkfont"];
                model.watermarkfontsize = Utils.StrToInt(collection["watermarkfontsize"].Trim(), 12);

                bll.saveConifg(model);
                AddAdminLog(RBSEnums.ActionEnum.Edit.ToString(), "修改系统配置信息"); //记录日志 
              
            }
            catch(Exception exception)
            {
                RBS.Core.Logs.LogManager.WriteLog("error","文件写入失败，请检查是否哟读写权限！");
            }


            return RedirectToAction("SysConfig");
        }  
        #endregion

    
        public ActionResult Test(int id = 1, string kword = null)
        {

             
            ChkAdminLevel("manager_log", RBSEnums.ActionEnum.View.ToString()); //检查权限  
            Dictionary<string, string> pagerParams = null;

            string strWhere = "id>0" + CombSqlTxt(kword);
            const string orderby = "add_time desc,id desc";
            var bll = new Core.BLL.manager_log(); 
            const int pageSize = 10;
            var startIndex =id; 

            int totalItems =0; //要分页的总记录数
            DataTable dt = bll.GetList(pageSize, startIndex, strWhere, orderby, out totalItems);
            //PagedList构造函数
            var list = IListDataSet.DataTableToIList<RBS.Core.Model.manager_log>(dt);
            var arts = new PagedList<RBS.Core.Model.manager_log>(list, id, pageSize, totalItems);
           return View(arts);
        }


        #region 友情链接
        public ActionResult LinkList(int id = 1, string kword = null)
        {
            const int pageSize = 10;
            ChkAdminLevel("#", RBSEnums.ActionEnum.View.ToString()); //检查权限
            var bll = new RBS.Core.BLL.Sys_Links();
            // var admin = GetAdminInfo(); //取得当前管理员信息
            if (kword != null) kword = kword.Replace("'", "");
            var strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(kword))
            {
               strTemp.Append(" and (LinkName like  '%" + kword + "%')");
            }
            string strWhere = strTemp.ToString();
            const string orderby = " Sequence  desc";
            var startIndex = id;

            int totalItems = 0; //要分页的总记录数
            DataTable dt = bll.GetList(pageSize, startIndex, strWhere, orderby, out totalItems).Tables[0];
            //PagedList构造函数 
            var list = IListDataSet.DataTableToIList<RBS.Core.Model.Sys_Links>(dt);
            PagedList<RBS.Core.Model.Sys_Links> arts = null;
            if (list != null)
                arts = new PagedList<RBS.Core.Model.Sys_Links>(list, id, pageSize, totalItems);
            else
            {
                list = new List<RBS.Core.Model.Sys_Links>();
                arts = new PagedList<RBS.Core.Model.Sys_Links>(list, id, pageSize, totalItems);
            }
            return View(arts);
        }
        //edit
        public ActionResult LinkEdit(int id = 0)
        {
            var model = new RBS.Core.Model.Sys_Links{IsDisplay = 1,Sequence = 100};
            if (id != 0)
            { 
                var bll = new RBS.Core.BLL.Sys_Links();
                model = bll.GetModel(id);
            }
            ViewData.Model = model;
            return View();
        }
        [HttpPost]
        public ActionResult LinkEdit(FormCollection collection)
        {

            var a = collection;
            var model = new RBS.Core.Model.Sys_Links
            {
                  LinkName =  collection["LinkName"],
                    LinkUrl =  collection["LinkUrl"],
                  IsDisplay = Convert.ToInt32(collection["IsDisplay"]),
                    Sequence =   Convert.ToInt32(collection["Sequence"]),
            };

            var bll = new RBS.Core.BLL.Sys_Links();
            if (collection["Id"] != "0")
            {
                model.Id = Convert.ToInt32(collection["Id"]);
                bll.Update(model);
                AddAdminLog(RBSEnums.ActionEnum.Edit.ToString(), "修改:" + model.Id); //记录日志
            }
            else
            {

                bll.Add(model);
                AddAdminLog(RBSEnums.ActionEnum.Add.ToString(), "添加:" + model.Id); //记录日志
            }
            return RedirectToAction("LinkList");
        }


        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult LinkDelete(string ids, string returnUrl)
        {
            var ret = new JsonReturnMessages();
            ChkAdminLevel("#", RBSEnums.ActionEnum.Delete.ToString()); //检查权限 
            try
            {
                foreach (var id in ids.TrimEnd(',').Split(',').ToList())
                {
                    new RBS.Core.BLL.Sys_Links().Delete(int.Parse(id));
                }
            }
            catch (Exception exception)
            {
                ret.IsSuccess = false;
                ret.Msg = "操作失败！";
                return Json(ret);
            }
            AddAdminLog(RBSEnums.ActionEnum.Delete.ToString(), "删除"); //记录日志
            ret.IsSuccess = true;
            ret.Msg = "操作成功";
            ret.Data = !string.IsNullOrEmpty(returnUrl) ? returnUrl : Url.Action("LinkList", "Sys");
            return Json(ret);
        }

        #endregion

    }
}
